from django.shortcuts import render
from django.views import View
from django.http import JsonResponse

from meiduo_mall.utils.cookiesecret import CookieSecret
from django_redis import get_redis_connection
import json
from goods.models import SKU

# Create your views here.

#购物车管理
class CartsView(View):

    #添加购物车
    def post(self, request):
        #接收和校验参数
        #接收参数
        user = request.user  #用户
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected', True)

        #判断参数是否正常
        if not all([sku_id, count]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必要参数'})

        #判断用户是否登陆

        if user.is_authenticated:
            #用户已登录，操作redis购物车
            conn = get_redis_connection('carts')    #５号
            #提取原有redis购物车数据
            redis_carts = conn.hgetall('carts_%s' % user.id)
            redis_selected = conn.smembers('selected_%s' % user.id)
            # (2)、构建最新的购物车数据 —— 存在则count累加，选中状态以最新为准
            # (3)、把新的购物车数据写入redis

            #如果商品已经存在就更新数据
            if str(sku_id).encode() in redis_carts:
                #个数累加
                #当前sku_id商品在redis购物车中
                count = count + int(redis_carts[str(sku_id).encode()])
                conn.hset('carts_%s' % user.id, sku_id, count)
            else:
                conn.hset('carts_%s' % user.id, sku_id, count)
            if selected:
                #被选中，需要把sku_id加入集合中
                conn.sadd('selected_%s' % user.id, sku_id)

            else:
                #如果商品已经不存在，请直接添加数据
                conn.srem('selected_%s' % user.id, sku_id)
            return JsonResponse({
                'code': 0,
                'errmsg': '添加购物车成功！'
            })
        else:
            #用户未登陆，操作cookie购物车
            cart_str = request.COOKIES.get('carts')
            #如果用户操作过cookie购物车
            if cart_str:
                #解密出明文
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}

            #判断要加入购物车的商品是否已经在购物车中，如果有相同商品，累加求和，反之赋值
            if sku_id in cart_dict:
                #累加求和
                cart_dict[sku_id]['count'] += count
                cart_dict[sku_id]['selected'] = selected
            else:
                cart_dict[sku_id] = {
                    'count': count,
                    'selected': selected
                }
            #把最新的购物车字典数据写入cookie中
            cart_str = CookieSecret.dumps(cart_dict)

            #构建响应
            response = JsonResponse({
                'code': 0,
                'errmsg': '添加购物车成功！'
            })
            response.set_cookie('carts', cart_str, max_age=24* 3600 *30)
            return response


    #展示购物车
    def get(self, request):
        #提取参数
        user = request.user
        cart_dict = {}
        if user.is_authenticated:
            #用户已登陆，查询redis购物车
            conn = get_redis_connection('carts')
            redis_carts = conn.hgetall('carts_%s' % user.id)
            redis_selected = conn.smembers('selected_%s' % user.id)

            for k, v in redis_carts.items():
                sku_id = int(k)
                count = int(v)
                cart_dict[sku_id] = {
                    "count": count,
                    "selected": k in redis_selected
                }

        else:
            #用户未登陆，查询cookies购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
        #构建响应
        cart_skus = []

        sku_ids = cart_dict.keys()

        for sku_id in sku_ids:
            sku = SKU.objects.get(pk=sku_id)

            cart_skus.append({
                    'id': sku.id,
                    'name': sku.name,
                    'default_image_url': sku.default_image.url,
                    'price': sku.price,
                    'count': cart_dict[sku_id]['count'],
                    'selected': cart_dict[sku_id]['selected']

             })
        return JsonResponse({
                'code': 0,
                'errmsg': 'OK',
                'cart_skus': cart_skus
        })


    #修改购物车
    def put(self, request):
        #接收和校验参数
        #接收参数
        user = request.user
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected', True)
        #判断参数是否齐全
        if not all([sku_id, count]):
            return JsonResponse({'code': 400, 'errmsg': '缺少参数'})
        #业务数据处理－－更新redis或cookie购物车数据

        if user.is_authenticated:
            #用户已登录，修改redis购物车
            #1、链接到redis
            conn = get_redis_connection('carts')
            conn.hset('carts_%s' % user.id, sku_id, count)
            #更新redis购物车的商品数量
            if selected:
                conn.sadd('selected_%s' % user.id, sku_id)
            else:
                conn.srem('selected_%s' % user.id, sku_id)
            sku = SKU.objects.get(pk=sku_id)
            #构建响应
            response = JsonResponse({
                'code': 0,
                'errmsg': 'ok',
                'cart_sku': {
                    'id': sku.id,
                    'count': count,
                    'selected': selected,
                    'name': sku.name,
                    'default_image_url': sku.default_image.url,
                    'price': sku.price,
                    'amount': sku.price * count
                }
            })
            return response

        else:
            #用户未登陆，修改cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}

            #更新覆盖原有数据
            if sku_id in cart_dict:
                cart_dict[sku_id]['count'] = count
                cart_dict[sku_id]['selected'] = selected

            #最新数据写入cookie
            cart_str = CookieSecret.dumps(cart_dict)
            sku = SKU.objects.get(pk=sku_id)

            #构建响应
            response = JsonResponse({
                'code': 0,
                'errmsg': 'ok',
                'cart_sku': {
                    'id': sku.id,
                    'count':cart_dict[sku_id]['count'],
                    'selected': cart_dict[sku_id]['selected'],
                    'name': sku.name,
                    'default_image_url': sku.default_image.url,
                    'price': sku.price,
                    'amount': sku.price * cart_dict[sku_id]['count']
                }
            })
            response.set_cookie('carts', cart_str, max_age=24 * 3600 * 30)
            return response



    #删除购物车
    def delete(self, request):
        #接收和校验参数
        #接收参数
        user = request.user
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')

        #校验参数
        if not sku_id:
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少参数'
            })

        #判断用户是否登陆
        if user.is_authenticated:
            #用户已登陆，删除redis购物车
            conn = get_redis_connection('carts')
            #根据用户id删除商品sku
            conn.hdel('carts_%s'% user.id, sku_id)
            conn.srem('selected_%s' % user.id, sku_id)
            #删除结束后，没有响应的数据，只需要响应状态码
            return JsonResponse({
                'code': 0, 'errmsg': '删除购物车成功！'
            })
        else:
            #用户未登陆，删除redis购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                #转成明文
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}

            #删除购物车字典中的sku_id
            if sku_id in cart_dict:
                cart_dict.pop(sku_id)

            #把新的购物车字典数据加密写入cookie
            cart_str = CookieSecret.dumps(cart_dict)
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie('carts', cart_str, max_age=24 * 3600 * 30)
            return response

#全选购物车
class CartsSelectAllView(View):
    def put(self, request):
        #接收和校验参数
        #判断用户是否登陆
        user = request.user
        data = json.loads(request.body.decode())
        selected = data.get('selected')
        #校验参数
        if not isinstance(selected, bool):
            return JsonResponse({'cpde': 400,
                                 'errmsg': '参数有误！'})
        #业务数据处理－－登陆
        if user.is_authenticated:
            #用户已登陆，操作redis购物车
            conn = get_redis_connection('carts')
            #获取redis购物车商品数据
            redis_carts = conn.hgetall('carts_%s' % user.id)
            #把全部sku_id加入集合或从集合中去除
            sku_ids = redis_carts.keys()
            if selected:
                #全部sku_id加入集合
                conn.sadd('selected_%s' % user.id, *sku_ids)
            else:
                #全部从集合中去除
                conn.srem('selected_%s' % user.id, *sku_ids)
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})
            return response
        else:
            #用户未登陆，操作cookie购物车
            #提取cookie购物车字典数据
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}
            #设置全选或取消
            sku_ids = cart_dict.keys()
            for sku_id in sku_ids:
                cart_dict[sku_id]['selected'] = selected
            #把新购物车字典写入cookie
            cart_str = CookieSecret.dumps(cart_dict)
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie('carts', cart_str, max_age=30 * 24* 3600)
            return response

#主页购物车简图
class CartsSimpleView(View):
    def get(self, request):
        #业务数据处理
        user = request.user
        #定义一个字典，用于记录
        cart_dict = {}
        if user.is_authenticated:
            #读redis
            conn = get_redis_connection('carts')
            redis_cart = conn.hgetall('carts_%s' % user.id)
            redis_selected = conn.smembers('selected_%s' % user.id)

            for sku_id in redis_selected:
                cart_dict[int(sku_id)] = {
                    'count': int(redis_cart[sku_id]),
                    'selected': sku_id in redis_selected
                }
        else:
            #读取cookie
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = CookieSecret.loads(cart_str)
            else:
                cart_dict = {}

            new_cart_dict = {}   #存储已勾选的商品
            sku_ids = cart_dict.keys()
            for sku_id in sku_ids:
                if cart_dict[sku_id]['selected']:
                    new_cart_dict[sku_id] = {
                        'count': cart_dict[sku_id]['count'],
                        'selected':cart_dict[sku_id]['selected']
                    }
            cart_dict = new_cart_dict

        #根据cart_dict，去读取musql商品相信信息，构建响应
        sku_ids = cart_dict.keys()
        cart_skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(pk=sku_id)
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict[sku_id]['count'],
                'default_image_url': sku.default_image.url

            })
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'cart_skus': cart_skus
        })

